/**
 * Bun Actor Example
 * 
 * A simple actor example that works with Bun without any native dependencies.
 * 
 * To run this example:
 * ```
 * bun run examples/bun-actor-example.ts
 * ```
 */

// 注意：这个文件只导入最基本的 actor 模块，避免所有可能的原生依赖
import { Actor } from '../src/actor/actor';
import { PID } from '../src/actor/pid';

// 定义一个简化版的 Context 接口
interface SimpleContext {
  self(): PID;
  message(): any;
  respond(message: any): void;
}

// 简单的消息类型
interface HelloMessage {
  name: string;
}

// 计数器消息类型
interface CounterMessage {
  value: number;
}

// 简单的 Actor 实现
class SimpleActor implements Actor {
  private count = 0;
  
  receive(context: SimpleContext): void {
    const message = context.message();
    
    // 打印消息类型
    console.log(`接收到消息类型: ${typeof message}`);
    
    // 处理不同类型的消息
    if (typeof message === 'string') {
      console.log(`收到字符串消息: ${message}`);
    } 
    else if (message && typeof message === 'object') {
      if ('name' in message) {
        // 处理 HelloMessage
        const helloMsg = message as HelloMessage;
        console.log(`你好, ${helloMsg.name}!`);
      } 
      else if ('value' in message) {
        // 处理 CounterMessage
        const counterMsg = message as CounterMessage;
        this.count += counterMsg.value;
        console.log(`计数器现在的值: ${this.count}`);
      }
    }
  }
}

// 主函数
async function main() {
  console.log('启动 Bun Actor 示例...');
  
  try {
    // 创建一个简化的 Props 对象
    const props = {
      producer: () => new SimpleActor(),
    };
    
    // 创建一个 PID
    const pid = new PID('local', `actor-${Date.now()}`);
    
    // 创建 actor 并存储
    const actor = props.producer();
    actors.set(pid.id, actor);
    console.log(`Actor 已创建，PID: ${pid.toString()}`);
    
    // 定义发送消息的函数
    const sendMessage = (pid: PID, message: any) => {
      const actor = actors.get(pid.id);
      
      if (actor) {
        // 创建简单的上下文
        const context: SimpleContext = {
          self: () => pid,
          message: () => message,
          respond: (response: any) => console.log(`响应: ${JSON.stringify(response)}`)
        };
        
        // 调用 actor 的 receive 方法
        actor.receive(context);
      } else {
        console.log(`找不到 Actor: ${pid.id}`);
      }
    };
    
    // 发送不同类型的消息
    console.log('\n发送字符串消息:');
    sendMessage(pid, 'Hello from Bun!');
    
    console.log('\n发送 Hello 消息:');
    sendMessage(pid, { name: 'Bun 用户' });
    
    console.log('\n发送 Counter 消息:');
    sendMessage(pid, { value: 10 });
    sendMessage(pid, { value: 5 });
    
    console.log('\n示例完成!');
  } catch (error) {
    console.error('示例运行出错:', error);
  }
}

// 存储 actor 的简单映射
const actors = new Map<string, Actor>();

// 运行示例
main().catch(console.error); 